<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btnConnect">连接到服务器</button>
    <br />
    <input type="text" id="content" />
    <button id="btnSend">发送消息</button>
    <br />
    <button id="btnClose">关闭连接</button>
  </body>
  <script>
    const btnConnect = document.getElementById("btnConnect");
    const txtContent = document.getElementById("content");
    const btnSend = document.getElementById("btnSend");
    const btnClose = document.getElementById("btnClose");

    let ws = null;

    btnConnect.addEventListener("click", () => {
      ws = new WebSocket("ws://localhost:9527");
      ws.onopen = function () {
        console.log("连接到了后台服务器");
      };
      ws.onclose = function (e) {
        console.log("关闭前端WebSocket");
      };
    });

    btnSend.addEventListener("click", () => {
      let content = txtContent.value;
      ws.send(content);
      ws.onmessage = function (e) {
        console.log(e.data);
      };
    });

    btnClose.addEventListener("click", () => {
      ws.close();
    });
    
  </script>
</html>
